#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "setupserial.h"
#include "serialinfo.h"
#include <QDebug>
#include <QTime>
#include <QMessageBox>
#include "textedit.h"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("测试串口调试助手程序");
    ui->btnSend->setEnabled(false);
    m_isopen = false;
    m_parity = 0;

    ui->line_msec->setText(QString::number(100));//定时发送默认ms数
    QRegExp rx("[0-9]+$");
    QRegExpValidator *validator = new QRegExpValidator(rx,this);
    ui->line_msec->setValidator(validator);

    ui->line_local_port->setValidator(validator);
    ui->line_remot_port->setValidator(validator);

    QRegExp rx1("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
    QRegExpValidator *validator1 = new QRegExpValidator(rx1,this);
    ui->line_remot->setValidator(validator1);
    ui->line_local->setValidator(validator1);
//    ui->line_remot->setInputMask("000.000.000.000;0");
//    ui->line_local->setInputMask("000.000.000.000;0");

    m_mode = M_WorkMode::Port_TcpS;
    /*定时发送 的connect*/
    m_timer = new QTimer(this);
    connect(m_timer,SIGNAL(timeout()),this,SLOT(slot_send_every()));
    connect(ui->chk_sendEvery,SIGNAL(toggled(bool)),this,SLOT(slot_start_timer(bool)));



    m_works = new Serialworks;
    slot_fresh_com();
    ui->cmb_bitrate->setCurrentIndex(7);

    connect(ui->action,SIGNAL(triggered(bool)),this,SLOT(slot_fresh_com()));
    connect(m_works,SIGNAL(signal_show_recv_com_data(QByteArray)),this,SLOT(slot_show_recv_com_data(QByteArray)));
    connect(ui->checkBox,SIGNAL(toggled(bool)),ui->textEdit_2,SLOT(slot_setChecked(bool)));

    connect(m_works,SIGNAL(signal_show_warning()),this,SLOT(slot_show_box()));


    ui->groupBox_3->setWindowFlags(Qt::WindowStaysOnTopHint);
    ui->groupBox->setVisible(false);
    connect(ui->cmb_serial,SIGNAL(currentIndexChanged(int)),this,SLOT(slot_curr_index_change(int)));

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::slot_fresh_com()
{
    SerialInfo info;
    QStringList list = info.comList;
    int count = ui->cmb_serial->count();
    if(count >3){
        for(int i=count-1;i>=3;i--){
            ui->cmb_serial->removeItem(i);
        }
    }
    ui->cmb_serial->insertItems(3,list);
}

void MainWindow::on_btn_clearWin_clicked()
{
    ui->textEdit->clear();
}

void MainWindow::on_btn_clearSend_clicked()
{
    ui->textEdit_2->clear();
}

void MainWindow::on_btn_openCom_clicked()
{
    if(!m_isopen){
        int temp =m_works->openCom(ui->cmb_serial->currentText(),ui->cmb_bitrate->currentText().toInt());
        if(!temp){
            QMessageBox::warning(this,"注意","当前串口无法打开，请检查(或刷新串口)后重新打开",QMessageBox::Ok);
            return ;
        }
        m_isopen = true;
        ui->cmb_bitrate->setEnabled(false);
        ui->cmb_serial->setEnabled(false);
        ui->btnSend->setEnabled(true);
        ui->btn_openCom->setText("关闭串口");
        m_works->start();
    }else
    {
        m_works->closeCom();

        ui->cmb_bitrate->setEnabled(true);
        ui->cmb_serial->setEnabled(true);
        m_isopen = false;
        ui->btnSend->setEnabled(false);
        ui->btn_openCom->setText("打开串口");
        ui->chk_sendEvery->setChecked(false);
    }

}

void MainWindow::on_btn_more_clicked()
{
    SetupSerial *setup = new SetupSerial(m_works,ui->cmb_serial->currentText(),ui->cmb_bitrate->currentText().toInt(),m_parity);
    int ret = setup->exec();
    if(ret ==QDialog::Accepted){
        ui->cmb_serial->setCurrentText(setup->comName());
        ui->cmb_bitrate->setCurrentText(QString::number(setup->Bitrate()));
        m_parity = setup->Parity();
    }
}

void MainWindow::slot_show_recv_com_data(QByteArray bytes){
    QString str ="["+QTime::currentTime().toString("hh:mm:ss:zzz")+ "]收<--◆" ;
    for(int i=0;i<bytes.length();i++){
        str += QString::number(uint(bytes.at(i)),16);
        str +=" ";
    }
    showEdit(str);
}

void MainWindow::slot_show_box()
{
   QMessageBox::warning(this,"注意","当前串口无法打开，请检查(或刷新串口)后重新打开",QMessageBox::Ok);
   ui->cmb_bitrate->setEnabled(true);
   ui->cmb_serial->setEnabled(true);
   ui->btnSend->setEnabled(false);
   ui->btn_openCom->setText("打开串口");
}


void MainWindow::on_btnSend_clicked()
{
    QString str="["+QTime::currentTime().toString("hh:mm:ss.zzz")+"]发-->◇";
    QString str1 = ui->textEdit_2->toPlainText();
    qDebug() <<"str1=" <<str1;
    if(str1.length() == 0)
        return ;

    if(ui->checkBox->isChecked())
    {
        QString str2 = str1.remove(" ");
        int len = str2.length()/2;
        char *p = new char[len];
        for(int i=0;i<len;i++)
        {
            bool ok;
            *(p+i) = str2.mid(i*2,2).toInt(&ok,16);
        }
        if(m_mode == M_WorkMode::Port_Com)
        {
            m_works->writeCom(p,len);
        }
        else if(m_mode==M_WorkMode::Port_TcpS)
        {
            m_server->sendData(ui->cmb_client_ip->currentText(),p,len);
        }




        delete p;
        p=NULL;
        //显示在textEdit
        QString str3="";
        for(int j=0;j<len;j++){
            str3 =str3+ str2.mid(j*2,2)+" ";
        }
        showEdit(str+str3);

    }
    else
    {
        if(m_mode == M_WorkMode::Port_Com)
        {
           m_works->writeCom(str1);

        }
        else if(m_mode == M_WorkMode::Port_TcpS)
        {
            m_server->sendData(ui->cmb_client_ip->currentText(),str1);
        }




        //显示在textEdit
        QString str2 = str1.toLatin1().toHex().toUpper();
        QString str3 = "";
        for(int i=0;i<str2.length();i+=2){
            str3 =str3 + str2.mid(i,2) +" ";
        }
        showEdit(str+str3);
    }
}

void MainWindow::showEdit(QString str)
{
    if(ui->textEdit->document()->toPlainText().length() > 10000000)
        ui->textEdit->clear();
    QTextCursor cursor = ui->textEdit->textCursor();
    cursor.movePosition(QTextCursor::End);
    ui->textEdit->setTextCursor(cursor);
    ui->textEdit->append(str);
}

void MainWindow::slot_send_every()
{
    if(ui->btnSend->isEnabled())
        ui->btnSend->click();

}

void MainWindow::slot_start_timer(bool chk)
{
    if(chk){
        int num =ui->line_msec->text().toInt();
        if(num){
            m_timer->start(num);
            ui->line_msec->setEnabled(false);
        }
        else{
            QMessageBox::about(this,"通知","请设置非零数据");
            ui->chk_sendEvery->setChecked(false);
        }
    }
    else
    {
        if(m_timer->isActive()){
            m_timer->stop();
            ui->line_msec->setEnabled(true);
        }
    }
}

void MainWindow::slot_curr_index_change(int index)
{
    switch(index){
    case 0:
        m_mode = M_WorkMode::Port_TcpS;
        ui->line_remot->setEnabled(false);
        ui->line_remot_port->setEnabled(false);
        ui->line_local_port->setEnabled(true);
        ui->btn_conn->setText("监听");
        ui->lbl_client_name->setVisible(true);
        ui->cmb_client_ip->setVisible(true);
        break;
    case 1:
        m_mode = M_WorkMode::Port_TcpC;
        ui->line_remot->setEnabled(true);
        ui->line_remot->setEnabled(true);
        ui->line_remot_port->setEnabled(true);
        ui->line_local_port->setEnabled(false);
        ui->lbl_client_name->setVisible(false);
        ui->cmb_client_ip->setVisible(false);
        ui->btn_conn->setText("连接");
        break;
    case 2:
        m_mode = M_WorkMode::Port_Udp;
        ui->line_remot->setEnabled(true);
        ui->line_remot_port->setEnabled(true);
        ui->line_local_port->setEnabled(true);
        ui->btn_conn->setText("连接");
        ui->lbl_client_name->setVisible(false);
        ui->cmb_client_ip->setVisible(false);
        break;
    case 3:
        m_mode = M_WorkMode::Port_Com;
        ui->lbl_client_name->setVisible(false);
        ui->cmb_client_ip->setVisible(false);
    }

    if(index>=0 && index<=2){
        ui->groupBox->hide();
        ui->groupBox_3->show();
        ui->groupBox_3->raise();
        //ui->groupBox_3->setWindowFlags(Qt::WindowStaysOnTopHint);//功能同上
    }
    else if(index >=3){
        ui->groupBox_3->hide();
        ui->groupBox->show();
        ui->groupBox->raise();
        //ui->groupBox->setWindowFlags(Qt::WindowStaysOnTopHint);//功能同上
    }
}

void MainWindow::on_btn_conn_clicked()
{

    if(m_mode == M_WorkMode::Port_TcpS){
        if(ui->line_local_port->text()==""){
            QMessageBox::information(this,"本地端口号不能为空","本地端口号不能为空",QMessageBox::Ok);
            return;
        }
        m_server = new Server();
        bool ok;
        m_server->init(ui->line_local->text(),ui->line_local_port->text().toInt(&ok,10));
        ui->btn_conn->setEnabled(false);
        ui->cmb_serial->setEnabled(false);
        connect(m_server,SIGNAL(signal_recv_data(QString,QByteArray)),this,SLOT(slot_server_recv_data(QString,QByteArray)));
        connect(m_server,SIGNAL(signal_socket_change(QString,bool)),this,SLOT(slot_server_socket_change(QString,bool)));//服务器的socket 状态改变
    }
    else if(m_mode == M_WorkMode::Port_TcpC){
        ;
    }
    else if(m_mode == M_WorkMode::Port_Udp){
        ;
    }

}

//服务器接收到的客户端的数据。
void MainWindow::slot_server_recv_data(QString ip,QByteArray bytes)
{
    QString str ="["+QTime::currentTime().toString("hh:mm:ss:zzz")+ "]收<--(" ;
    str = str + ip +":)";

    for(int i=0;i<bytes.length();i++){
        str += QString::number(uint(bytes.at(i)),16);
            str +=" ";
    }
    showEdit(str);
}

//客户端的QComboBox 的选项增加 或者减少
void MainWindow::slot_server_socket_change(QString ip,bool isconn)
{
    if(isconn)
    {
        if(ui->cmb_client_ip->findText(ip)==-1)
            ui->cmb_client_ip->addItem(ip);
    }
    else
    {
        for(int i=0;i<ui->cmb_client_ip->count();i++)
        {
            if(ui->cmb_client_ip->itemText(i) == ip)
            {
                ui->cmb_client_ip->removeItem(i);
                break;
            }
        }
    }

    if(ui->cmb_client_ip->count()>0){
        if(!ui->btnSend->isEnabled())
            ui->btnSend->setEnabled(true);
    }
    else
        ui->btnSend->setEnabled(false);

}


// tcp  通讯的关闭监听或者连接。
void MainWindow::on_btn_discon_clicked()
{
    ui->btn_conn->setEnabled(true);
    m_server->closeServer();
    ui->btnSend->setEnabled(false);
    ui->cmb_serial->setEnabled(true);
}

